import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {HttpService} from "./http.service";
import {PathService} from "./path.service";
import {FileDesc} from "../model/file-view";
import {Result} from "../model/restful";
import {Observable} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class FileModifyService {

  constructor(
    private server: HttpService,
    private httpClient: HttpClient,
    private pathService: PathService
  ) {
  }

  rename(file: FileDesc, newName: string): Observable<Result<any>>  {
    const form = {
      path: file.path,
      filename: file.filename,
      newName: newName
    }
    return this.httpClient.post<Result<any>>(this.server.baseUrl() + '/file/rename', form)
  }

  deleteFile(file: FileDesc): Observable<Result<any>> {
    const form = FileModifyService.genFormByFile(file)
    return this.httpClient.post<Result<any>>(this.server.baseUrl() + '/file/delete', form)
  }

  createFile(path: string, filename: string): Observable<Result<any>> {
    const form = FileModifyService.genForm(path, filename)
    return this.httpClient.post<Result<any>>(this.server.baseUrl() + '/file/createFile', form)
  }

  createDir(path: string, dirname: string): Observable<Result<any>> {
    const form = FileModifyService.genForm(path, dirname)
    return this.httpClient.post<Result<any>>(this.server.baseUrl() + '/file/createDir', form)
  }

  private static genFormByFile(file: FileDesc): any {
    return FileModifyService.genForm(file.path, file.filename)
  }

  private static genForm(filepath: string, filename: string): any {
    return {
      path: filepath,
      filename: filename
    }
  }
}
